import { Document, Font, Image, Page, StyleSheet, Text, View, pdf } from '@react-pdf/renderer';
import print from 'print-js';
import QRCode from 'qrcode';
import { formatData, getGoodsNum, isShowEyeInfo, isShowFrameInfo, museText } from './Detail';

export const printBillPDF = async (data: any, pdfBlob?: Blob): Promise<Blob> => {
  if (!pdfBlob) {
    console.info(pdfBlob);
    const codeStr = await QRCode.toDataURL(data.pay_qr_code_url || ' ', { margin: 0 });
    const dom = <RenderBillPDF data={data} qrCode={codeStr} />;
    await new Promise((resolve) => setTimeout(() => resolve(true), 100));
    pdfBlob = await pdf(dom).toBlob();
  }
  print(URL.createObjectURL(pdfBlob));
  return pdfBlob;
};

const splitText = (text: string, charLen: number): string => {
  if (text.length > charLen) {
    const t1 = text.substring(0, charLen);
    const t2 = text.substring(charLen);
    return t1 + ' ' + splitText(t2, charLen);
  }
  return text;
};

const specsNameSplit = (specsName: string) => {
  const lineLen = 10;
  const res = [], arr = specsName.split('，');
  let tmp = '';
  for (let idx in arr) {
    let text = arr[idx];
    if ((idx as any) != arr.length - 1) {
      text = text + ',';
    }
    if (text.length > lineLen) {
      if (tmp != '') {
        res.push(tmp, ' ');
        tmp = '';
      }
      res.push(text.substring(0, lineLen), ' ');
      const tmpText = text.substring(lineLen);
      if (tmpText.length > lineLen) {
        // 一般单个规格不会有更长的了
        res.push(tmpText.substring(0, lineLen), ' ');
        tmp += tmpText.substring(lineLen);
      } else {
        tmp += text.substring(lineLen);
      }
    } else {
      if ((tmp + text).length > lineLen) {
        res.push(tmp, ' ');
        tmp = '';
      }
      tmp += text;
    }
  }
  res.push(tmp);
  return res.join('');
};

const RenderBillPDF = ({ data, qrCode }: { data: any, qrCode: string }) => {
  const showEyeInfo = isShowEyeInfo(data);
  const showFrameInfo = isShowFrameInfo(data);
  return <Document>
    <Page size={[609.45, 396.85]} style={{ padding: 16, fontFamily: 'song' }}>
      <Text style={styles.title}>票据单</Text>
      {/* 头部信息 */}
      <View style={styles.rowDirection}>
        <View style={{ flexDirection: 'column', fontSize: 10.5 }}>
          <View style={[styles.rowDirection, { paddingBottom: 3 }]}>
            <Text style={{ width: '34%' }}>单据号：{data.order_id}</Text>
            <Text style={{ width: '41%' }}>归属科室：眼视光中心</Text>
            {/* <View style={{ width: '41%', flexDirection: 'row' }}>
              <Text style={{ width: 53 }}>归属科室：</Text>
              <Text style={{ width: 150 }}> {splitText(data.create_dept_name, 13)}</Text>
            </View> */}
            <Text style={{ width: '20%' }}>科室电话：0736-7788032</Text>
          </View>
          <View style={[styles.rowDirection, { paddingTop: 3 }]}>
            <Text style={{ width: '34%' }}>患者姓名：{data.patient_name}</Text>
            <Text style={{ width: '41%' }}>身份证/住院号：{data.identity_no}</Text>
            <Text style={{ width: '20%' }}>手机号：{data.mobile}</Text>
          </View>
        </View>
        {/* 二维码 */}
        <Image src={qrCode} style={{ width: 74, height: 60, marginTop: -32, paddingLeft: 4 }} />
      </View>
      {/* 商品信息 */}
      <View style={{ marginTop: 6, border: 0.5, fontSize: 10.5, textAlign: 'center' }}>
        <Text style={{ borderBottom: 0.5, padding: 3 }}>
          商品信息
        </Text>
        <View style={[styles.rowDirection, { borderBottom: 0.5 }]}>
          <Text style={[styles.tableColumn, { width: '10%' }]}>分类</Text>
          <Text style={[styles.tableColumn, { width: '10%' }]}>品牌</Text>
          <Text style={[styles.tableColumn, { width: '10%' }]}>商品名称</Text>
          <Text style={[styles.tableColumn, { width: '14%' }]}>商品编号</Text>
          <Text style={[styles.tableColumn, { width: '20%' }]}>规格（单位）</Text>
          <Text style={[styles.tableColumn, { width: '8%' }]}>单价</Text>
          <Text style={[styles.tableColumn, { width: '6%' }]}>数量</Text>
          <Text style={[styles.tableColumn, { width: '8%' }]}>原价</Text>
          <Text style={[styles.tableColumn, { width: '6%' }]}>折扣</Text>
          <Text style={[styles.tableColumn, { width: '8%', borderRight: 0 }]}>折扣价</Text>
        </View>
        {
          (data.order_goods_list as Array<any> ?? []).map((curr, idx, arr) => {
            return <View style={[styles.rowDirection, idx === arr.length - 1 ? {} : { borderBottom: 0.5 }]}>
              <Text style={[styles.tableColumn, { width: '10%' }]}>{splitText(curr.class_name ?? ' ', 5)}</Text>
              <Text style={[styles.tableColumn, { width: '10%' }]}>{splitText(curr.brand_name, 5)}</Text>
              <Text style={[styles.tableColumn, { width: '10%' }]}>{splitText(curr.goods_name, 5)}</Text>
              <Text style={[styles.tableColumn, { width: '14%' }]}>{curr.goods_id}</Text>
              <Text style={[styles.tableColumn, { width: '20%' }]}>{specsNameSplit(curr.specs_name)}</Text>
              <Text style={[styles.tableColumn, { width: '8%' }]}>{curr.goods_price}</Text>
              <Text style={[styles.tableColumn, { width: '6%' }]}>{curr.goods_num}</Text>
              <Text style={[styles.tableColumn, { width: '8%' }]}>{curr.goods_total_price}</Text>
              <Text style={[styles.tableColumn, { width: '6%' }]}>{curr.discount}</Text>
              <Text style={[styles.tableColumn, { width: '8%', borderRight: 0 }]}>{curr.discount_price}</Text>
            </View>
          })
        }
      </View>
      {
        /* 验光信息 */
        showEyeInfo &&
        <View style={{ marginTop: 9, border: 0.5, fontSize: 10.5, textAlign: 'center' }}>
          <View style={[styles.rowDirection, { borderBottom: 0.5 }]}>
            <Text style={[styles.tableColumn, { width: '11%' }]}>眼别</Text>
            <Text style={styles.tableColumn}>球镜</Text>
            <Text style={styles.tableColumn}>柱镜</Text>
            <Text style={styles.tableColumn}>轴位</Text>
            <Text style={[styles.tableColumn, { width: '11%' }]}>矫正前视力</Text>
            <Text style={[styles.tableColumn, { width: '11%' }]}>矫正后视力</Text>
            <Text style={styles.tableColumn}>离焦量</Text>
            <Text style={styles.tableColumn}>瞳距</Text>
            <Text style={[styles.tableColumn, { width: '10%' }]}>总瞳距</Text>
            <Text style={[styles.tableColumn, { borderRight: 0 }]}>瞳高</Text>
          </View>
          <View style={{ flexDirection: 'row' }}>
            <View style={[styles.tableColumn2, { width: '11%' }]}>
              <Text style={[styles.tableCell2]}>右眼 (R)</Text>
              <Text style={[styles.tableCell2]}>左眼 (L)</Text>
            </View>
            <View style={[styles.tableColumn2]}>
              <Text style={styles.tableCell2}>{formatData(data.right_degrees)}</Text>
              <Text style={styles.tableCell2}>{formatData(data.left_degrees)}</Text>
            </View>
            <View style={[styles.tableColumn2]}>
              <Text style={styles.tableCell2}>{formatData(data.right_astig)}</Text>
              <Text style={styles.tableCell2}>{formatData(data.left_astig)}</Text>
            </View>
            <View style={[styles.tableColumn2]}>
              <Text style={styles.tableCell2}>{data.right_axial ?? ' '}</Text>
              <Text style={styles.tableCell2}>{data.left_axial ?? ' '}</Text>
            </View>
            <View style={[styles.tableColumn2, { width: '11%' }]}>
              <Text style={[styles.tableCell2]}>{data.right_rectify_bef ?? ' '}</Text>
              <Text style={[styles.tableCell2]}>{data.left_rectify_bef ?? ' '}</Text>
            </View>
            <View style={[styles.tableColumn2, { width: '11%' }]}>
              <Text style={[styles.tableCell2]}>{data.right_rectify_af ?? ' '}</Text>
              <Text style={[styles.tableCell2]}>{data.left_rectify_af ?? ' '}</Text>
            </View>
            <View style={[styles.tableColumn2]}>
              <Text style={styles.tableCell2}>{data.right_defocus ?? ' '}</Text>
              <Text style={styles.tableCell2}>{data.left_defocus ?? ' '}</Text>
            </View>
            <View style={[styles.tableColumn2]}>
              <Text style={styles.tableCell2}>{data.pup_distance_right ?? ' '}</Text>
              <Text style={styles.tableCell2}>{data.pup_distance_left ?? ' '}</Text>
            </View>
            <View style={[styles.tableColumn2, { width: '10%' }]}>
              <Text style={[styles.tableCell2, { height: 37, paddingTop: 12 }]}>{data.pup_distance ?? ' '}</Text>
            </View>
            <View style={[styles.tableColumn2, { borderRight: 0 }]}>
              <Text style={styles.tableCell2}>{data.pup_high_right ?? ' '}</Text>
              <Text style={styles.tableCell2}>{data.pup_high_left ?? ' '}</Text>
            </View>
          </View>
          <View style={[styles.rowDirection]}>
            <Text style={[styles.tableColumn, { textAlign: 'left', width: '50.5%', paddingLeft: 9 }]}>用途：{museText[data?.muse] || '-'}</Text>
            <Text style={[styles.tableColumn, { textAlign: 'left', width: '49.5%', borderRight: '0', paddingLeft: 6 }]}>ADD：{data.madd}</Text>
          </View>
        </View>
      }
      {
        /* 镜架信息 */
        showFrameInfo &&
        <View style={[styles.rowDirection, { marginTop: 9, border: 0.5, fontSize: 10.5, textAlign: 'center' }]}>
          <Text style={[styles.tableColumn, { width: '10%', paddingTop: 13 }]}>
            镜架信息
          </Text>
          <View style={{ width: '90%' }}>
            <View style={[styles.rowDirection, { borderBottom: 0.5 }]}>
              <Text style={[styles.tableColumn, { width: '12%' }]}>框宽</Text>
              <Text style={[styles.tableColumn, { width: '12%' }]}>框高</Text>
              <Text style={[styles.tableColumn, { width: '12%' }]}>中梁</Text>
              <Text style={[styles.tableColumn, { width: '14%' }]}>镜对角直径</Text>
              <Text style={[styles.tableColumn, { width: '16%' }]}>型号</Text>
              <Text style={[styles.tableColumn, { width: '16%' }]}>框型</Text>
              <Text style={[styles.tableColumn, { width: '18%', borderRight: 0 }]}>是否需要防滑套</Text>
            </View>
            <View style={[styles.rowDirection]}>
              <Text style={[styles.tableColumn, { width: '12%' }]}>{data.frame_width || '-'}</Text>
              <Text style={[styles.tableColumn, { width: '12%' }]}>{data.frame_height || '-'}</Text>
              <Text style={[styles.tableColumn, { width: '12%' }]}>{data.frame_middle || '-'}</Text>
              <Text style={[styles.tableColumn, { width: '14%' }]}>{data.frame_diagonal || '-'}</Text>
              <Text style={[styles.tableColumn, { width: '16%' }]}>{data.frame_model || '-'}</Text>
              <Text style={[styles.tableColumn, { width: '16%' }]}>{data.frame_material || '-'}</Text>
              <Text style={[styles.tableColumn, { width: '18%', borderRight: 0 }]}>{data.is_slip === 'Y' ? '需要' : '不需要'}</Text>
            </View>
          </View>
        </View>
      }
      {
        /* 验光医生信息 */
        showEyeInfo &&
        <View style={[styles.rowDirection, { padding: '6 0', fontSize: 10.5, borderBottom: 0.5 }]}>
          <Text style={{ width: '40%' }}>验光号：{data.sight_no || '-'}</Text>
          <Text style={{ width: '40%' }}>就诊医生：{data.doctor_name || '-'}</Text>
          <Text>验光师：{data.optician_name || '-'}</Text>
        </View>
      }
      {/* 底部汇总信息 */}
      <View style={{ fontSize: 10.5 }}>
        <View style={[styles.rowDirection, { padding: '9 0 3' }]}>
          <Text style={{ width: '28%' }}>订单编号：<Text style={{ fontSize: 10.5 }}>{data.order_id}</Text></Text>
          <Text style={{ width: '28%' }}>创建时间：<Text style={{ fontSize: 10.5 }}>{data.create_date + ' ' + data.create_time}</Text></Text>
          <Text style={{ width: '22%' }}>订单状态：{orderStatus[data.order_status]}</Text>
          <Text style={{}}>发票：{data.is_ballot === 'Y' ? '已开具' : '未开'}</Text>
        </View>
        <View style={[styles.rowDirection, { padding: '3 0' }]}>
          <Text style={{ width: '28%' }}>商品原价：{data.goods_total_price} (元)</Text>
          <Text style={{ width: '28%' }}>商品数量：{getGoodsNum(data.order_goods_list, 'goods_num')} (件)</Text>
          <Text style={{ width: '22%' }}>订单金额：{data.total_price} (元)</Text>
          <Text style={{}}>订单折扣：{data.discount_ratio}</Text>
        </View>
        <View style={[styles.rowDirection, { padding: '3 0' }]}>
          <Text style={{ width: '28%' }}>应收款：{data.sett_price} (元)</Text>
          <Text style={{ width: '28%' }}>欠款：{parseFloat(data.owing_price ?? 0).toFixed(2)} (元)</Text>
          <Text style={{ width: '22%' }}>邮寄费：{parseFloat(data.franking ?? 0).toFixed(2)} (元)</Text>
          <Text style={{}}>结算价格：{data.sett_price} (元)</Text>
        </View>
        <View style={[styles.rowDirection, { padding: '3 0' }]}>
          <Text style={{ width: '28%' }}>收件人：{data.frank_name || '-'}</Text>
          <Text style={{ width: '28%' }}>收件人电话：{data.frank_phone || '-'}</Text>
          <Text style={{}}>收件人地址：<Text style={{ fontSize: 9 }}>{data.frank_address || '-'}</Text></Text>
        </View>
      </View>
    </Page>
  </Document>;
};

const orderStatus = {
  'C': '已开单',
  'W': '待支付',
  'P': '已支付',
  'F': '已完成',
  'E': '已作废',
  'A': '退款待审批',
  'R': '已退款',
  'U': '退款处理中'
};

const styles = StyleSheet.create({
  title: {
    fontSize: 15,
    fontWeight: 'bold',
    textAlign: 'center',
    margin: '8 0 20'
  },
  rowDirection: {
    flexDirection: 'row'
  },
  tableColumn: {
    borderRight: 0.5,
    padding: 3,
    width: '9.5%'
  },
  tableColumn2: {
    borderRight: 0.5,
    width: '9.5%'
  },
  tableCell2: {
    padding: 3,
    borderBottom: 0.5
  }
});

Font.register({ family: 'song', fonts: [{ src: '/fonts/ShuSong.ttf' }] });
